import 'dart:async';

import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_all.dart';

// 验证码按钮
class XinDongCountdownButtonCtr extends GetxController {
  static XinDongCountdownButtonCtr get to => Get.find();

  final int timeInterval = XinDongAll.instance.isRelease ? 60 : 8;

  // 私有属性变量
  int _timeCount = 0;
  String _autoCodeText = "获取验证码";
  Timer? _timer;
  bool _isActive = true;

  @override
  void dispose() {
    resetAction();
    super.dispose();
  }

  void start() {
    startTimerAction();
  }

  void reset() {
    resetAction();
  }

  // 开启定时器
  void startTimerAction() {
    // 避免重复 - 已经存在且正在活跃计时中的，忽略
    if (_timer != null && _timer?.isActive == true) {
      return;
    }

    // 重置
    _timeCount = timeInterval;
    _autoCodeText = "$_timeCount s";
    _isActive = false;
    update();

    // 如果已存在先取消置空
    _timer = null;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _timeCount -= 1;
      if (_timeCount <= 0) {
        timer.cancel();
        _isActive = true;
      }

      if (_timeCount <= 0) {
        _autoCodeText = "获取验证码";
      } else {
        _autoCodeText = "$_timeCount s";
      }
      update();
    });
  }

  // 手动重置 - 重新获取
  void resetAction() {
    _timer?.cancel();
    _timer = null;
    _autoCodeText = "获取验证码";
    update();
  }
}

// 验证码按钮
class XinDongCountdownButton extends StatelessWidget {
  final Function() onTapSend;

  const XinDongCountdownButton({Key? key, required this.onTapSend}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 36,
      child: GetBuilder<XinDongCountdownButtonCtr>(
        builder: (provider) {
          if (provider.timeInterval == 0) {
            return const SizedBox();
          }
          return TextButton(
            onPressed: provider._isActive ? onTapSend : null,
            style: ButtonStyle(
              padding: MaterialStateProperty.all(EdgeInsets.zero),
              textStyle: MaterialStateProperty.all(const TextStyle(fontSize: 16, fontWeight: FontWeight.normal)),
              shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0))),
              // 文字颜色
              foregroundColor: MaterialStateProperty.resolveWith((states) {
                if (states.contains(MaterialState.disabled)) {
                  return DZColors.disabledColor;
                }
                return DZColors.mainColor;
              }),
              // 背景颜色
              backgroundColor: MaterialStateProperty.resolveWith((states) {
                return Colors.transparent;
              }),
            ),
            child: Text(provider._autoCodeText),
          );
        },
      ),
    );
  }
}
